package com.myproject.jianghu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myproject.jianghu.annotation.AccessCheck;
import com.myproject.jianghu.utils.JwtTokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myproject.jianghu.entity.UserInstance;
import com.myproject.jianghu.service.RoleService;
import com.myproject.jianghu.service.UserService;
import com.myproject.jianghu.utils.Constants;
import com.myproject.jianghu.utils.Result;
import com.myproject.jianghu.utils.ReturnFormat;

@Controller
public class LoginController {

	Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Resource
	private UserService userService;

	@Resource
	private RoleService roleService;

	@Autowired
	JwtTokenUtils jwtTokenUtils;
	
	@RequestMapping(value = "/index")
	public String indexPage() {
		return "index";
	}
	

	@AccessCheck
	@ResponseBody
	@RequestMapping(value = "/loginPage")
	public String loginPage(@RequestParam(value = "error", required = false) String error, Model model) {
		System.out.println("登录页");
//		if (error != null) {
//			model.addAttribute("error", "登陆失败");
//			return "loginFailure";
//
//		}
		return "common/loginPage";
	}

	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	@ResponseBody
	public Result login(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map resultMap = new HashMap();
//		String requestIp = AccessObjectUtil.getIpAddress(request);
//		System.out.println(requestIp);
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String validateCode = request.getParameter("validateCode");
		System.out.println("account:" + account + "---password" + password);
		UserInstance user=userService.validateLoginUser(account, password);
		System.out.println(user==null);
		boolean authed = false;
		if(validateCode.equals("")&&user!=null) {
			authed=true;
		}
		if (authed) {
			// return "index";
			String userToken = jwtTokenUtils.generateToken(user);
//			List<?> roleList = roleService.getRolesByUser(account);

			response.setHeader("access_token",userToken);
			logger.info("登陆成功"+account);
			return ReturnFormat.retParam(1112, "登录成功");
		} else {
			return ReturnFormat.retParam(1012, "登录失败");
		}
	}

	@RequestMapping(value = "/register/sendValidateCode")
	@ResponseBody
	public String sendValidateCode(HttpServletRequest request) {
		String status = "1";
		String mobileNumber = request.getParameter("mobilenumber");
		System.out.println(mobileNumber);
		int min = 100000;
		int max = 999999;
		Random random = new Random();
		int s = random.nextInt(max) % (max - min + 1) + min;
		// 向用户发送验证码的方法

		//
		System.out.println(s);
//		MemCachedUtil.add(mobileNumber, s);
		return status;
	}

	@RequestMapping(value = "/user/register", method = RequestMethod.POST)
	@ResponseBody
	public Result doRegister(HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String confirm_password = request.getParameter("confirm_password");
		String mobileNumber = request.getParameter("mobileNumber");
		UserInstance user = userService.getUserByMobile(mobileNumber);
		if(user!=null) {
			return ReturnFormat.retParam(1011, null);
		}		
		String validateCode = request.getParameter("validateCode");
//		String code = MemCachedUtil.get(mobileNumber) + "";
		if (!password.equals(confirm_password)) {
			return ReturnFormat.retParam(1012, null);
		}

		if (validateCode.equalsIgnoreCase("aaaa") || validateCode.equalsIgnoreCase("AAAA")) {
			Map<String, String> params = new HashMap<String, String>();
			params.put("username", username);
			params.put("password", password);
			params.put("mobile", mobileNumber);
			System.out.println(params);
			// 将用户保存到数据库中
			int resultCode =userService.doRegister(params);
			// 清楚缓存
//			MemCachedUtil.delete(mobileNumber);
			if(resultCode==1) {
				return ReturnFormat.retParam(1111, null);
			}
		}

		return ReturnFormat.retParam(1111, null);
	}
	
	@RequestMapping(value="isLogined")
	@ResponseBody
	public Result isLogined(HttpServletRequest request,HttpServletResponse response) {
//		String userToken = CookieUtil.getCookie(request, Constants.USERTOKEN);
		boolean flag=false;
		Result result=null;
//		if (StringUtils.isBlank(userToken)) {
//			return ReturnFormat.retParam(1110, flag);	
//		}else {
//			String userName=(String)MemCachedUtil.get(userToken);
//			if(StringUtils.isNotBlank(userName)) {
//				return ReturnFormat.retParam(1112, true);
//			}
//		}
		return result;		
	}
	
	@RequestMapping(value="/logout")
	public Result doLogOut(HttpServletRequest request,HttpServletResponse response) {
//		String userToken = CookieUtil.getCookie(request, Constants.USERTOKEN);
		boolean flag=false;
		Result result=null;
//		if (StringUtils.isBlank(userToken)) {
//			return ReturnFormat.retParam(1110, flag);	
//		}else {
//			String userName=(String)MemCachedUtil.get(userToken);
//			if(StringUtils.isNotBlank(userName)) {
//				MemCachedUtil.delete(userToken);//清除缓存
//				return ReturnFormat.retParam(1112, true);
//			}
//		}		
		return result;
	}

}
